import http from "node:http";
import RequestParser from "../request/RequestParser";
import os from "node:os";
import Action from "./action/Action";
import actionRegistrar from "./action/ActionRegistrar";
import ResponseParser from "../request/ResponseParser";
import * as process from "node:process";
import AnsiText from "../utils/AnsiText";
import ActionInterceptor from "./interceptor/ActionInterceptor";
import actionInterceptorRegistrar from "./interceptor/ActionInterceptorRegistrar";
import actionStaticLoader from "./static/ActionStaticLoader";
import ActionParam from "./action/ActionParam";

export type NodeActionConfigType = {
    port: number | undefined
}

class NodeAction {

    // 版本
    version: string = '${nodeActionVersion}'
    // http 服务
    server: http.Server | undefined
    // 配置
    config: NodeActionConfigType = {
        // 端口号
        port: undefined
    }
    // 初始化时间
    initTime: number | undefined

    constructor() {
        this.initTime = Date.now();
    }

    private _request(server: http.Server) {
        const _this = this
        server.on('request', function (request: http.IncomingMessage, response: http.ServerResponse) {
            try {
                RequestParser.parse(request, response).then(actionParam => {
                    RequestParser.resolve(actionParam).then(res => {
                        if (!!_this.actionResultHandler) {
                            // 结果处理
                            res = _this.actionResultHandler(actionParam, res)
                        }
                        ResponseParser.resolve(actionParam, res)
                    }).catch(e => {
                        // 请求截止
                    })
                }).catch(error => {
                    _this.actionErrorHandler(request, response, error);
                })
            } catch (e) {
                _this.actionErrorHandler(request, response, e)
            }
        })
    }

    /**
     * 启动服务
     */
    start(): NodeAction {
        const startTime = Date.now()
        const server = this.server = http.createServer();
        // 加载静态文件
        actionStaticLoader.load()
        // 监听请求
        this._request(server)
        server.listen(this.config.port, () => {
            // @ts-ignore
            const port = server.address().port

            let networkAddress = ''

            try {
                // 获取网络接口的 IP 地址并输出
                const interfaces = os.networkInterfaces();
                for (let iface in interfaces) {
                    interfaces[iface]?.forEach(function (details) {
                        if (details.family === "IPv4" && !details.internal) {
                            networkAddress = `http://${details.address}:${port}`
                        }
                    });
                }
            } catch (e) {
            }

            const endTime = Date.now()
            const useTime = endTime - (this.initTime || startTime) + ' ms'

            const logTexts = [
                '\n  ',
                AnsiText.text(`NodeAction(v${this.version}) Server `).set('cyan', 'bold').out(),
                AnsiText.text('is running in ').set('white').out(),
                AnsiText.text(useTime).set('bold').out(),
                '\n\n',
                '  ',
                AnsiText.text('🌏 Local:   ').set('bold').out(),
                'http://localhost:' + port,
                '\n',
                '  ',
                AnsiText.text('🌐 Network: ').set('bold').out(),
                networkAddress,
                '\n'
            ]

            process.stdout.write(logTexts.join(''))
        })
        return this
    }

    /**
     * 设置服务端口号
     * @param {number} port 端口号
     */
    port(port: number): NodeAction {
        this.config.port = port;
        return this
    }

    /**
     * 添加控制器
     * @param {Action[]} actions 控制器
     */
    actions(actions: Action[]): NodeAction {
        actionRegistrar.adds(actions)
        return this
    }

    /**
     * 添加拦截器
     * @param {ActionInterceptor[]} interceptors 拦截器
     */
    interceptors(interceptors: ActionInterceptor[]) {
        actionInterceptorRegistrar.adds(interceptors)
        return this
    }

    /**
     * 请求异常处理器
     * @param {http.IncomingMessage} request 请求
     * @param {http.ServerResponse} response 响应
     * @param {any} error 异常
     */
    actionErrorHandler(request: http.IncomingMessage, response: http.ServerResponse, error: any) {
        console.error(error)
    }

    /**
     * 响应结果处理器
     * @param {ActionParam} actionParam 控制器参数
     * @param {any} res 返回数据
     */
    actionResultHandler(actionParam: ActionParam, res: any) {
        return res
    }
}

const nodeAction = new NodeAction();
export default nodeAction
